package com.blog.study.study7;

/**
 * 〈一道面试题〉<br>
 *
 * @author 未绪
 * @time 2017/12/3 18:31
 */
public class QuestionOne {

    Business business;

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 100; i++) {

            }

        new QuestionOne().init();
    }

    public void init() throws InterruptedException {
        business = new Business();
        //题目要求
        //建立一个线程用于输出信息
        //在主线程中进行输入操作

        new Thread(() -> {
            //新建的线程用于输出信息
            while (true) {
                synchronized (QuestionOne.class) {

                    business.output();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        //主线程中用于输入信息
        while (true) {
            synchronized (QuestionOne.class) {
                business.input();
                Thread.sleep(1000);
            }
        }
    }
}

class Business {

    private static boolean flag = true;

    public void input() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //输入十次
            for (int i = 0; i < 10; i++) {
                System.out.println("Input的次数为：" + i);
            }
            flag = false;
            this.notifyAll();
        }
    }

    public void output() {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //输出五次
            for (int i = 0; i < 5; i++) {
                System.out.println("Output的次数为：" + i);
            }
            flag=!flag;
            this.notifyAll();
        }
    }

}